<template>
  <div class="mg16 flex">
    <left :setpData="setpData" :content="contentLeft"></left>
    <div class="apply_right" v-if="!isStep2">
      <steps-demo :stepsObj="stepsObj"></steps-demo>
      <div class="right_form">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="会议名称" prop="title">
            <el-input
              v-model="ruleForm.title"
              placeholder="请输入会议名称"
              class="wid450"
            ></el-input>
          </el-form-item>
          <el-form-item label="会议时间" prop="StartTime">
            <el-date-picker
              v-model="Times"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              class="wid450"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeTime"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="产品分类" prop="immsortThree">
            <el-cascader
              v-if="showvideo"
              ref="areaCascader"
              v-model="ProductClassification"
              class="formWidthdpl300"
              :props="CPprops"
              @change="changeImmsort"
            />
          </el-form-item>
          <el-form-item label="领域分类" prop="imIndustrytwo">
            <el-cascader
              v-if="showvideo"
              v-model="DomainClassification"
              ref="areaCascader2"
              class="formWidthdpl300"
              :props="props2"
              @change="changeImIndustry"
            />
          </el-form-item>
          <el-form-item label="会议类型" required>
            <el-radio-group v-model="ruleForm.isCharges">
              <el-radio :label="0">免费会议</el-radio>
              <el-radio :label="1">付费会议</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="ff_body" v-if="ruleForm.isCharges==1">
            <div class="flex f_c">
              <span> <span style="color: red">*</span> 会议报名费用：</span>
              <el-input
                class="wid270"
                v-model="shareInfo.money"
              ></el-input>
              <span>元/人</span>
            </div>
            <div class="flex f_c">
              <span><span style="color: red">*</span> 对公打款户名：</span>
              <el-input
                class="wid270"
                v-model="shareInfo.accountname"
              ></el-input>
            </div>
            <div class="flex f_c">
              <span><span style="color: red">*</span> 对公打款开户行:</span>
              <el-input
                class="wid270"
                v-model="shareInfo.bankname"
              ></el-input>
            </div>
            <div class="flex f_c">
              <span><span style="color: red">*</span> 对公打款账号：</span>
              <el-input
                class="wid270"
                v-model="shareInfo.bankcardid"
              ></el-input>
            </div>
            <div class="bd_meet_body">
              <div class="bd_meet">
                <div>
                  <span class="fs16 bold">绑定指定会议：</span>
                  <span
                    >用户只需付费报名其中的一个会议，便同时报名了其他的相关会议</span
                  >
                </div>
                <el-button type="text" icon="el-icon-circle-plus-outline" @click="bdMeetdialog=true;bindingMeet=''"
                  >绑定会议</el-button
                >
              </div>
              <div class="meet_list" v-for="(item,index) in ruleForm.shareMeetingList" :key="item.mid">
                <span>{{ index+1 }} . {{ item.title }}</span>
                <el-button type="text" @click="delbdMeet(item)">删除</el-button>
              </div>
            </div>
          </div>

          <el-form-item label="大会介绍" prop="contentHtml">
            <div style="width: 60%" v-if="showvideo">
              <Ueditor
                ref="ue"
                :value="defaultMSGPc"
                style="width: 100%"
                :ueditor-config="ueditorConfig"
                @ready="editorReady"
              />
            </div>
            <!-- <p class="hint">
            1、请不要在详细描述中含有联系方式，如电话，QQ，手机等联系方式，网站提供统一的联系方式入口；
          </p>
          <p class="hint">
            2、上传图片前请确保图片来源合规，注意避免图片侵权风险；
          </p> -->
          </el-form-item>
        </el-form>
        <div class="right_btm">
          <el-button @click="saveDrafts()">保存草稿箱</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >下一步</el-button
          >
        </div>
      </div>
    </div>
    <div class="apply_right" v-if="isStep2">
      <steps-twos :isStep2="isStep2" :firstFrom="firstFrom" @isleave="isleave"></steps-twos>
    </div>
    <el-dialog
        title="绑定会议"
        :visible.sync="bdMeetdialog"
        width="600px"
        center
        :close-on-click-modal="false"
      >
        <div style="text-align: center; margin-bottom: 20px">
          <span>
            请选择会议：
          </span>
          <el-select class="wid450" v-model="bindingMeet"  placeholder="默认字段">
            <el-option
              v-for="item in bindingMeetData"
              :key="item.mid"
              :label="item.title"
              :value="item.mid"
            ></el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer" style="margin: 20px 0">
          <el-button type="primary" @click="sureBinding()">确定</el-button>
        </span>
      </el-dialog>
  </div>
</template>
  
  <script>
import Ueditor from "@/components/UEditor";
import left from "@/views/selfCreate/components/left.vue";
import stepsDemo from "@/views/selfCreate/components/Steps.vue";
import stepsTwos from "./step2.vue";
import axios from "axios";
import api from "@/api/index";
import Cookies from 'js-cookie'
import { changeDateFormat7 } from "@/utils/commin";
export default {
  components: {
    left,
    stepsDemo,
    Ueditor,
    stepsTwos,
  },
  data() {
    return {
      setpData: {
        step: 1,
        stepExamineOneStatus: 2,
        stepExaminetwoStatus: 1,
      },
      contentLeft:{
        title:'定制研讨会',
        content:'定制研讨会为预约审核机制，审核通过后，开启会议直播'
      },
      firstFrom: {},
      showvideo: true,
      stepsObj: {
        list: [
          "填写会议信息",
          "设置会议主题和嘉宾",
          "进行会议设置",
          "会议预约审核",
        ],
        nums: 1,
      },
      bdMeetdialog:false,
      radio: 3,
      isCanleave: false, // 是否可以离开当前页面
      isStep2: false,
      ProductClassification: [],
      DomainClassification: [],
      CPprops: {
        lazy: true,
        lazyLoad: this.getLazyload, // 产品分类
      },
      props2: {
        lazy: true,
        lazyLoad: this.getLazyload2, // 领域分类
      },
      ruleForm: {
        isCharges: 0,
        title: "",
        //内容分类
        contentType: "",
        //开始时间
        StartTime: "",
        VideoEndDate: "",
        //大会简介
        contentHtml: "",
        //行业产品线
        imIndustryone: "",
        imIndustryoneName: "",
        imIndustrytwo: "",
        imIndustrytwoName: "",
        immsortOne: "",
        immsortOneName: "",
        immsortThree: "",
        immsortThreeName: "",
        immsortTwo: "",
        immsortTwoName: "",
        shareMeetingList:[]
      },
      shareInfo: {
          accountname: "",
          bankname: "",
          bankcardid: "",
          money: "",
        },
      contentTypeData: [
        { name: "原理知识", value: "1" },
        { name: "方法应用", value: "2" },
        { name: "维护维修", value: "3" },
        { name: "数据处理", value: "4" },
        { name: "产品介绍", value: "5" },
      ],
      defaultMSGPc: "",
      instance: "",
      ueditorConfig: {
        toolbars: [
          ['fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'pasteplain', '|', 'forecolor', 'backcolor', 'selectall', '|',
            'fontfamily', 'fontsize', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'link', 'unlink', '|',
            'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify',
            '|',
            'insertimage', 'attachment', 'spechars', 'insertvideo', 'word2html', 'insertunorderedlist', '|',
            'inserttable', 'deletetable', 'mergecells', 'mergeright', 'mergedown']
        ]
      },
      rules: {
        title: [{ required: true, message: "请输入会议名称", trigger: "blur" }],
        contentType: [
          { required: true, message: "请选择内容分类", trigger: "change" },
        ],
        immsortThree: [
          { required: true, message: "请选择产品分类", trigger: "change" },
        ],
        imIndustrytwo: [
          { required: true, message: "请选择领域分类", trigger: "change" },
        ],
        StartTime: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        contentHtml: [
          { required: true, message: "请填写大会介绍", trigger: "blur" },
        ],
      },
      Times: [],
      bindingMeetData:[],
      bindingMeet:'',
    };
  },
  mounted() {

    //从列表进来
    if (this.$route.query.mid) {
      this.getMeetingInfo();
    }
    //从草稿箱进来
    if (this.$route.query.id) {
      this.getDraftsMeetingInfo();
    }
    this.selectChargedMeeting()
  },
  methods: {
    isleave(val){
      this.isCanleave = val;
    },
    changeTime(){
    this.ruleForm.StartTime=this.Times[0]
    this.ruleForm.VideoEndDate=this.Times[1]
  },
    sureBinding(){
      if (this.bindingMeet=='') {
        this.$message({type:'error',message:'请选择会议'})
        return false
      }
      let form=this.bindingMeetData.filter(item=>{
        if(item.mid==this.bindingMeet){
            return item
        }
      })
      let form2={
        mid: form[0].mid,
        shareid: form[0].shareid,
        title:  form[0].title,
      }
      this.ruleForm.shareMeetingList=[]
      this.ruleForm.shareMeetingList.push(form2)
      this.bdMeetdialog=false
    },
    selectChargedMeeting(){
        let form = {
        imshowid: this.$store.getters.imShowId,
        mid: this.$route.query.mid,
      };
      api.selfMeting.selectChargedMeeting(form).then((res) => {
        this.bindingMeetData = res.data;
      });
    },
    delbdMeet(val){
      this.ruleForm.shareMeetingList=this.ruleForm.shareMeetingList.filter(item=>{
        if(item.mid!=val.mid){
            return item
        }
      })
    },
    getDraftsMeetingInfo() {
      this.showvideo=false
      let form = {
        id: this.$route.query.id,
        imshowId: this.$store.getters.imShowId,
      };
      api.selfMeting.getMeetingDraftById(form).then((res) => {
        this.ruleForm = JSON.parse(res.data.meetinginfo);
        if (this.ruleForm.imIndustrytwo) {
          this.DomainClassification.push(Number(this.ruleForm.imIndustryone));
          this.DomainClassification.push(Number(this.ruleForm.imIndustrytwo));
        }
        if (this.ruleForm.immsortThree) {
          this.ProductClassification.push(Number(this.ruleForm.immsortOne));
          this.ProductClassification.push(Number(this.ruleForm.immsortTwo));
          this.ProductClassification.push(Number(this.ruleForm.immsortThree));
        }
        this.Times.push(this.ruleForm.StartTime)
        this.Times.push(this.ruleForm.VideoEndDate)
        this.ruleForm.StartTime = changeDateFormat7(this.ruleForm.StartTime);
        setTimeout(() => {
          this.showvideo = true;
        }, 1000);
      });
    },
    saveDrafts() {
      let form = {
        company: this.$store.state.root.companyData.webinarCompanyName,
        imshowid: this.$store.getters.imShowId,
        meettype: this.$route.query.meetType,
        meetinginfo: JSON.stringify(this.ruleForm),
      };
      //判断从定制厂商会进来
      if (this.$route.query.meetType) {
        form.meettype = this.$route.query.meetType;
      }

      if (this.$route.query.id) {
        form.id = this.$route.query.id;
      }
      api.selfMeting.saveMeetingDraft(form).then((res) => {
        this.$message({ type: "success", message: "保存成功！" });
        this.isCanleave = true;
     
        if(this.$route.query.meetType){
          if (this.$route.query.meetType==3) {
            this.$router.push('/selfCreate/selfMeting')
          }else{
            this.$router.push('/custoMade/index')
          }
        }else{
          this.$router.push('/selfCreate/selfMeting')
        }
      });
    },
    changeImmsort(val) {
      this.ruleForm.immsortOne = val[0];
      this.ruleForm.immsortTwo = val[1];
      this.ruleForm.immsortThree = val[2];
      this.$nextTick(() => {
        let data = this.$refs["areaCascader"].getCheckedNodes(false);
        this.ruleForm.immsortOneName = data[0].pathLabels[0];
        this.ruleForm.immsortTwoName = data[0].pathLabels[1];
        this.ruleForm.immsortThreeName = data[0].pathLabels[2];
      });
    },
    changeImIndustry(val) {
      this.ruleForm.imIndustryone = val[0];
      this.ruleForm.imIndustrytwo = val[1];
      this.$nextTick(() => {
        let data = this.$refs["areaCascader2"].getCheckedNodes(false);
        this.ruleForm.imIndustryoneName = data[0].pathLabels[0];
        this.ruleForm.imIndustrytwoName = data[0].pathLabels[1];
      });
    },
    getMeetingInfo() {
      this.showvideo = false;
      let form = {
        imshowId: this.$store.getters.imShowId,
        mid: this.$route.query.mid,
      };
      api.selfMeting.getMeetingInfo(form).then((res) => {
        this.ruleForm = res.data;
        if (this.ruleForm.imIndustrytwo) {
          this.DomainClassification.push(Number(this.ruleForm.imIndustryone));
          this.DomainClassification.push(Number(this.ruleForm.imIndustrytwo));
        }
        if (this.ruleForm.immsortThree) {
          this.ProductClassification.push(Number(this.ruleForm.immsortOne));
          this.ProductClassification.push(Number(this.ruleForm.immsortTwo));
          this.ProductClassification.push(Number(this.ruleForm.immsortThree));
        }
        this.Times.push(this.ruleForm.StartTime);
        this.Times.push(this.ruleForm.VideoEndDate);
    
        this.ruleForm.StartTime = changeDateFormat7(this.ruleForm.StartTime);
        if (this.ruleForm.shareInfo) {
            this.shareInfo=this.ruleForm.shareInfo 
        }
        
        setTimeout(() => {
          this.showvideo = true;
        }, 1000);
      });
      this.defaultMSGPc = this.ruleForm.contentHtml;
    },
    editorReady(instance) {
      this.instance = instance;
      instance.setContent(this.ruleForm.contentHtml);
      instance.addListener("contentChange", () => {
        this.ruleForm.contentHtml = instance.getContent();
        this.ruleForm.content= instance.getContentTxt()
        this.againValidate();
      });
    },
    againValidate() {
      this.$refs.ruleForm.validate((vaild) => {});
    },
    // 获取产品分类内容
    getLazyload(node, resolve) {
      if (!node) {
        return false;
      }
      const { level } = node;

      axios(
        `https://gateway.instrument.com.cn/classificationMonitoring/classify/getPrincipleClassifySelectByParentId?parentId=${
          level == 0 ? 0 : node.value
        }`,
        { headers: { "Content-type": "application/x-www-form-urlencoded" } }
      ).then((res) => {
        // 换成你的接口方法
        if (res.data.code == 1) {
          resolve(
            res.data.data.map((val) => {
              return {
                value: val.id,
                label: val.name,
                leaf: level >= 2, // 因为省市区三项，所以第三次点击就不用在加载了，所以 >=2
              };
            })
          );
        }
      });
    },
    // 获取领域分类内容
    getLazyload2(node, resolve) {
      if (!node) {
        return false;
      }
      const { level } = node;
      axios(
        `https://gateway.instrument.com.cn/classificationMonitoring/classify/getIndustryClassifySelectByParentId?parentId=${
          level == 0 ? 0 : node.value
        }`,
        { headers: { "Content-type": "application/x-www-form-urlencoded" } }
      ).then((res) => {
        // 换成你的接口方法
        if (res.data.code == 1) {
          resolve(
            res.data.data.map((val) => {
              return {
                value: val.id,
                label: val.name,
                leaf: level >= 1, // 因为省市区三项，所以第三次点击就不用在加载了，所以 >=2
              };
            })
          );
        }
      });
    },
    submitForm(formName) {
        const passwordValid = Cookies.get('passwordValid')
  const username = Cookies.get('username')
  const mobile = Cookies.get('mobile')
  const CheckValid = Cookies.get('CheckValid')
   if (mobile && passwordValid && username && CheckValid) {

   
      this.$refs[formName].validate((valid) => {
        if (valid) {
            if (this.ruleForm.isCharges==1) {
                if(this.shareInfo.accountname==''){
                this.$message({type:'error',message:'请输入对公打款户名'})
                return false
            }
            if(this.shareInfo.bankname==''){
                this.$message({type:'error',message:'请输入对公打款开户行:'})
                return false
            }
            if(this.shareInfo.bankcardid==''){
                this.$message({type:'error',message:'请输入对公打款账号：'})
                return false
            }
            if(this.shareInfo.money==''){
                this.$message({type:'error',message:'请输入会议报名费用：'})
                return false
            }
            }
    
          this.ruleForm.shareInfo=this.shareInfo
          this.isStep2 = true;
          this.firstFrom = this.ruleForm;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }else{
      var _this = this;
      _this.isCanleave = true;
      this.$router.push('/login?type=sign')
    }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  beforeRouteLeave: function (to, from, next) {
    var _this = this;
    if (_this.isCanleave) {
      next();
    } else {
      next(false);
      setTimeout(() => {
        _this
          .$confirm("系统可能不会保存您所做的更改。", "离开此页面？", {
            confirmButtonText: "离开",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            _this.isCanleave = true;
            next();
          })
          .catch(() => {
            next(false);
            // cancelButton回调，把当前页路由推回
            // 不能使用this.$router进行路由操作，会触发beforeRouteLeave导致死循环
            window.history.pushState("", "", _this.currentUrl);
          });
      }, 300);
    }
  },
};
</script>
  
  <style lang="scss" scoped>
.wid450 {
  width: 450px !important;
}
.wid270 {
  width: 270px !important;
  margin: 0 20px;
}
.f_c {
  align-items: center;
  margin-bottom: 20px;
}
.formWidthdpl300 {
  width: 300px !important;
}
.wid200 {
  width: 200px !important;
}
.ff_body {
  width: 782px;
  min-width: 730px;
  padding: 24px 33px;
  background: #f9fafd;
  margin-bottom: 26px;
  margin-left: 20px;
  display: inline-block;
  .bd_meet_body {
    background: #f0f2f8;
    .bd_meet {
      @include flex(row, center, space-between);
      padding: 5px 24px;
      border-bottom: 1px solid #e5eaf0;
      font-size: 14px;
      color: #202933;
    }
    .meet_list {
      padding: 0px 24px;
      @include flex(row, center, space-between);
      padding-bottom: 6px;
    }
  }
}
.apply_right {
  margin-left: 16px;
  flex-grow: 1;
  width: 50%;
  background: #fff;
  .right_form {
    padding: 32px;
    border-top: 1px solid #f0f3f7;
  }
}
.apply_right2 {
  flex-grow: 1;
  width: 50%;
  background: #fff;
}
.right_btm {
  margin-top: 100px;
  padding-top: 24px;
  border-top: 1px solid #e5eaf0;
  text-align: center;
}
::v-deep .el-dialog__footer {
  padding-top: 0px;
  // border-top: 1px solid #e5eaf0;
}
::v-deep .el-dialog__header {
  background: #f5f8fc;
  text-align: left;
  font-size: 16px;
  color: #202933;
  padding: 11px 16px;
}
::v-deep .el-dialog__body {
  padding: 25px 25px 10px !important;
}
::v-deep .el-dialog__title {
  font-size: 16px;
}
::v-deep .el-form-item__label {
  text-align: left !important;
}
:v-deep .el-form-item:last-child {
  margin-bottom: 0px;
}
</style>